<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>公告管理</title>
    <link rel="stylesheet" href="/leek_bbs/statics/yu-ui/js_css/yu.css">
    <link rel="stylesheet" href="/leek_bbs/statics/layui/css/layui.css">
    <style>

        a { color:blue; transition:0.5s; }
        a:hover { color:red; }
        .layui-layout-admin .layui-footer{
            left: 0px;
            width: 98%;
        }
    </style>

</head>
<body style="background-color: #F2F2F2">

<div class="layui-layout layui-layout-admin" id="hmc">

    <div style="background-color: #FFFFFF">
        <!-- 内容主体区域 -->
        <div class="layui-tab layui-tab-brief" lay-filter="demo" lay-allowClose="true" >
            <div class="layui-tab-content">
                <div class="layui-tab-item layui-show">
                    <form class="layui-form">
                        <div class="layui-form-item marg">
                            <form class="layui-form">
                                <div class="layui-form-item marg" style="margin-left: 42px">
                                    <div class="layui-inline">
                                        <div class="layui-input-inline">
                                            <input type="text" id="nTitle" placeholder="公告标题..." name="nTitle" autocomplete="off" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline" style="width: 100px;">
                                            <input type="text" id="start_time" name="start_time" placeholder="开始时间..." autocomplete="off" class="layui-input">
                                        </div>
                                        <div class="layui-form-mid">-</div>
                                        <div class="layui-input-inline" style="width: 100px;">
                                            <input type="text" id="end_time" name="end_time" placeholder="结束时间..." autocomplete="off" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline">
                                            <input type="text" id="nContent" name="nContent" placeholder="内容查询..." autocomplete="off" class="layui-input">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-form-item marg" style="margin-left: 42px">
                                    <div class="layui-inline">
                                        <div class="layui-input-inline">
                                            <!--<input type="text" id="plate_name" name="plate_name" placeholder="帖子所在板块..." autocomplete="off" class="layui-input">-->
                                            <select name="plateName" lay-verify="" id="plateId">
                                                <option value="" selected>请选择一个板块</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline">
                                            <div class="layui-input-inline">
                                                <input type="text" id="anotherName" name="anotherName" placeholder="版主查询..." autocomplete="off" class="layui-input">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline"><!--data-type="search"-->
                                            <button type="button"  lay-submit lay-filter="searchBtn" data-type="search" id="search" class="layui-btn layui-btn-warm layui-icon layui-icon-search">查询</button>
                                                <button type="reset" class="layui-btn layui-icon layui-icon-refresh-1 layui-btn-normal">重置</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </form>

                    <table class="layui-hide" id="searchReload" lay-data="{id: 'idTest'}" lay-filter="test"></table>

                    <!-- 自定义按钮 -->
                    <div style="display: none;" id="cellphoneToo">
                        <div class="layui-btn-group">
                            <button type="button" class="layui-btn layui-btn-sm" lay-event="deleteNotices">批量删除</button>
                        </div>
                    </div>

                    <!-- 自定义操作按钮 -->
                    <div id="cellphoneBar" >
                        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete" >删除</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="layui-footer">
        <!-- 底部固定区域 -->
        <div align="center">
            © 凛冬 - 版权所有
        </div>

    </div>
</div>
<script src="/leek_bbs/statics/component/common_import.js"></script>

<script>
    var tableLoad;
    getPlateList(); //加载版块信息
    layui.define(['table','element','laydate','form'], function(exports){
        var table = layui.table;
        var element = layui.element;
        var laydate = layui.laydate;
        var form = layui.form;

        //日期时间范围
        laydate.render({
            elem: '#start_time'
            ,type: 'datetime'
        });
        laydate.render({
            elem: '#end_time'
            ,type: 'datetime'
        });
        Loading(" ");   //初始化加载数据
        function Loading(map) {
            //表格数据渲染必须函数
            tableLoad = table.render({
                elem: '#searchReload'	//表格操作对象
                ,url:'/leek_bbs/stair/noticeManage/getNoticeInfo'	//数据接口
                //,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                ,toolbar: '#cellphoneToo'	//自定义表格上面左侧按钮
                , method: 'post'
                , contentType: 'application/json'
                ,defaultToolbar: ['filter', 'exports']
                ,height:540     //固定表格高度,当每页要显示的条数大于10条时,让它出现下拉框
                ,cellMinWidth:100	//设置列的最小默认宽度,拉伸时最小能缩小的宽度
                , request: {
                    pageName: 'pageCurrent' //页码的参数名称，默认：page
                    , limitName: 'pageSize' //每页数据量的参数名，默认：limit
                }
                ,done:function(res,curr,count){
                    pageCurr = curr;
                }
                ,where:map
                ,text:{
                    none:'暂无相关数据'//默认:无数据
                }
                ,page: true
                ,limits:[10,20,30,40]	//每页显示条数选择下拉框
                ,title: '公告信息数据表'	//数据导出标题
                ,cols: [[
                    {type: 'checkbox', fixed: 'left'}	//复选框,多选
                    ,{field:'n_id', title:'ID',fixed: 'left', unresize: true, sort: true}//sort:已请求数据排序开启
                    ,{field:'n_title', title:'标题',id:'userName'}	//edit:可编辑数据 align:center居中显示
                    ,{field:'n_content', title:'内容'}
                    ,{field:'n_time',title:'发表时间',templet:function (d) {
                            return formDate(d.n_time)
                        }}
                    ,{field:'n_in_plate_name', title:'所属版块'}
                    ,{field:'another_name', title:'发表版主'}
                    ,{fixed: 'right', align:'center',width:200,title:'操作', toolbar: '#cellphoneBar'}	//toolbar可使用默认提供按钮,也可自定义按钮
                ]]
                //,id: 'Reload'     //重载标识

            });
        }
        function search(map){
            //执行重载
            table.reload('searchReload', {
                url: '/leek_bbs/stair/noticeManage/getNoticeInfo'
                ,methods:"post"
                ,request: {
                    pageName: 'pageCurrent' //页码的参数名称，默认：page
                    , limitName: 'pageSize' //每页数据量的参数名，默认：limit
                }
                ,page: {
                    curr: 1 //重新从第 1 页开始
                }
                ,where: {       //可以传对象
                    'userName': userName,
                    'phone': phone,
                    'anotherName': anotherName,
                    'beginRegister':beginRegister,
                    'endRegister':endRegister,
                    'userStatus':userStatus
                    //执行重载
                }
            }, 'data');
        }
        //表格重载
        var $ = layui.$, active = {

        };
        //监听搜索按钮
        $('#search').on('click', function(){
            var type = $(this).data('type');
            console.log(type);
            active[type] ? active[type].call(this) : '';
        });
        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data;    //表格选中的数据
            console.log(obj.config);
            switch(obj.event){
                case 'add':
                   // layer.alert(JSON.stringify(data));
                    addUser();
                    break;
                case 'deleteNotices':
                    //layer.alert(JSON.stringify(data));
                    //layer.msg('选中了：'+ data.length + ' 个');
                    var ids = new Array(data.length);
                    for (var i in data) {
                        var id = data[i].n_id;
                        ids[i] = id;
                    }
                   // var ids =JSON.stringify(ids);
                    layer.confirm('确定要删除此'+data.length+'行数据么', function(){
                        deleteNoticeByIds(ids)
                        layer.closeAll();
                    });
                    break;
                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
            };
        });

        //监听行工具事件
        table.on('tool(test)', function(obj){
            var data = obj.data;
            var ids = [];
            //console.log(obj)
            if(obj.event === 'edit'){
                layer.open({
                    type: 2,
                    title:'版块公告编辑',
                    content: '/leek_bbs/stair/a/b/admin/notice-edit',
                    area: ['100%', '100%'],
                    success:function (layero,index) {
                        var iframe = window['layui-layer-iframe' + index];
                        iframe.child(data,tableLoad)
                    }
                })
               /* layer.prompt({
                    formType: 2
                    ,value: data.email
                }, function(value, index){
                    obj.update({
                        email: value
                    });
                    layer.close(index);
                });*/
            }else if(obj.event ==='delete'){
                layer.confirm('确定删除此条公告吗?', function(index){
                    var id = [data.n_id]
                    deleteNoticeByIds(id)
                    layer.closeAll()
                });
            }
        });

        form.on('submit(searchBtn)',function (data) {
            let data2 =data.field;
            Loading(data2)
            //search(data2)
            console.log(data2)
            /*axios.post("/leek_bbs/stair/noticeManage/getNoticeInfo",data2).then((response)=>{
                console.log(response);
            })*/
           // console.log(data.field)
        })
    });

    //对要输出的时间进行格式化处理
    function formDate(dateStr) {
        var date = new Date(dateStr);
        var y = date.getFullYear();
        var m = (date.getMonth()+1).toString().padStart(2,"0");
        var d = date.getDate().toString().padStart(2,"0");
        var hh = date.getHours();
        var mm = date.getMinutes().toString().padStart(2,"0");
        //使用Es6属性进行字符串拼接
        return `${y}-${m}-${d} ${hh}:${mm}`;
    };

    //增加用户
   function addUser() {
       layui.use(['layer','form'],function () {
           var form = layui.form;
           layer.open({
               type: 1,
               id: 'addUser', //id唯一标识
               title: '添加用户',
               content: `<div style="margin-top: 30px;">
            <form class="layui-form" lay-filter="registerForm">
                <div class="layui-form-item">
                    <label class="layui-form-label">昵称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="another_name" lay-verify="required" autocomplete="off" placeholder="请输入昵称" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="username" lay-verify="required" autocomplete="off" placeholder="请输入用户名" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-inline">
                        <input type="password" name="password" placeholder="请输入密码" lay-verify="required|password" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">确认密码</label>
                    <div class="layui-input-inline">
                        <input type="password" name="pwd" placeholder="请再次输入密码" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">Email</label>
                    <div class="layui-input-inline">
                        <input type="email" name="email" lay-verify="required|email" autocomplete="off" placeholder="请输入邮箱地址" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block" style="margin-bottom: 52px;margin-top: -34px;">
                        <span id="errorRes" style="margin-left:0;font-size: 18px;color: red;"></span>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block" style="margin-top: -40px;">
                      <button type="submit" class="layui-btn btn-bg" lay-submit="" lay-filter="registerBtn">注册</button>
                      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
            </div>`,
               anim: 2,    //动画
               /*shade: 1,*/
               fixed: false,
               maxmin: false,   //最大化
               resize: false,  //关闭拉伸
               //scrollbar: false,   //不允许出现滚动条
               area: ['100%', '100%'],
               success: function (layero, index) {
                   $("#layui-layer"+index).find(".layui-layer-title").addClass("lay-head-title");
               }
           })
           form.on('submit(registerBtn)',function (data) {
               //alert(JSON.stringify(data.field))
               var data = data.field;
               //console.log(data.field)
               if (data.password != data.pwd) {

                   layer.msg('两次密码不一致', {icon: 5,time: 2000});
               }else {
                   axios.post("/leek_bbs/stair/userManage/addUser",data
                   ).then((response)=>{
                       console.log(response)
                       let resdata =response.data;
                       if (resdata.code == "500020") {     //用户注册成功
                           layer.msg('<img src="/leek_bbs/statics/yu-ui/images/ui-success.png">&emsp;用户注册成功', {
                               time: 2000 //2秒关闭（如果不配置，默认是3秒）
                           }, function(){
                               tableLoad.reload();
                               layer.closeAll();
                           });
                       }else if (resdata.code == "300022"){    //用户存在
                           $("#errorRes").text(resdata.msg);
                       } else {   //用户注册失败
                           layer.msg('<img src="/leek_bbs/statics/yu-ui/images/ui-error.png">&emsp;'+resdata.msg, {
                               time: 3000 //2秒关闭（如果不配置，默认是3秒）
                           });
                       }
                   })
               }
               return false;
           })

           //自定义验证规则  
           form.verify({
               password: [
                   /^[\S]{6,12}$/
                   ,'密码必须6到16位，且不能出现空格'
               ]
               ,phone: [/^1[3|4|5|7|8]\d{9}$/, '手机号格式不对！']
               ,email: [/^[a-z0-9._%-]+@([a-z0-9-]+\.)+[a-z]{2,4}$|^1[3|4|5|7|8]\d{9}$/, '邮箱格式不对']
           });
       })
   }
   //通过id删除公告
    function deleteNoticeByIds(ids) {
        axios.post("/leek_bbs/stair/noticeManage/deleteNoticeById",
            ids
        ).then((response)=>{
            console.log(response.data.code)
            if (response.data.code=='500020'){
                ui.success("删除成功",1500,true)
            }else{
                ui.success("删除失败",1500,true)
            }
            //刷新表格
            tableLoad.reload();
        })
    }
    var listPlate;
    function getPlateList(){
        axios.get('/leek_bbs/bbs/plate/findAll').then(result => {
            listPlate = result.data;
            listPlate.forEach(item => {
                let str = `<option value="${item.plate_name}">${item.plate_name}</option>`;
                $("#plateId").append(str);
            })
        }).catch(error => {
            ui.error("数据请求异常",1500,false);
        })
    }
    function getPlateInfo() {
        return listPlate;
    }
</script>

</body>
</html>